package org.interactive.spring.intro.controller.rest;

import org.interactive.spring.intro.exceptions.UserNotFoundException;
import org.interactive.spring.intro.exceptions.ValidationException;
import org.interactive.spring.intro.service.UsersService;
import org.interactive.spring.intro.transport.GenericResponse;
import org.interactive.spring.intro.transport.UserTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.interactive.spring.intro.transport.UsersResponse;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;
import java.util.List;

/**
 * UsersControllerImpl class
 *
 * @author bogdan.solga
 *
 * Date: 05.06.2013, time: 09:50
 */
@Controller
public class UsersControllerImpl implements UsersController {

    private static final Logger log = LoggerFactory.getLogger(UsersControllerImpl.class);

    @Autowired
    private UsersService usersService;

    public UsersResponse getUserByUserName(@PathVariable String userName) throws UserNotFoundException {
        UsersResponse response = new UsersResponse();

        UserTO userTO = usersService.getByUserName(userName);
        if (userTO != null) {
            response.setUsers(Arrays.asList(userTO));
        } else {
            response.setErrorMessage("There is no user with the username '" + userName + "'");
        }

        return response;
    }

    @Override
    public UsersResponse getAll(@RequestParam(required = false) String name) {
        UsersResponse response = new UsersResponse();

        List<UserTO> userTO = usersService.getAllUsers(name);
        if (userTO != null) {
            response.setUsers(userTO);
        } else {
            response.setErrorMessage("There are no users with the name '" + name + "'");
        }

        return response;
    }

    @Override
    public GenericResponse save(@RequestBody UserTO user) throws ValidationException {
        GenericResponse response = new GenericResponse();

        usersService.save(user);

        return response;
    }
}

